﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using AbstraX;
using AbstraX.Contracts;
using SolutionFramework.Entities;
using Microsoft.Practices.Unity;
using MvvmTreeView;
using System.Windows.Threading;
using AbstraX.ClientInterfaces;
using DataBindings.Services;

namespace DataBindings
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            ProviderClientManager.Initialize(null);

            var container = ProviderClientManager.Container;

            InitializeComponent();

            container.RegisterType(typeof(IBindingsTreeService), typeof(BindingsTreeService));
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var container = ProviderClientManager.Container;
            var viewModel = container.Resolve<IBindingsViewModel>();
            var context = new SolutionFrameworkDomainContext();
            var messageQueue = new Queue<string>();
            var waiting = false;

            ProviderClientManager.StatusLabel = this.StatusBar;
            ProviderClientManager.SetStatus("Initializing...");

            viewModel.TreeView.InternalTreeView = BindingsTreeView.InternalTreeView;
            viewModel.TreeView.Busy += new MvvmTreeView.BusyHandler(TreeView_Busy);
            viewModel.TreeView.OnStatus += new StatusHandler(TreeView_OnStatus);

            cmdBuild.Command = viewModel.BuildCommand;
            cmdBuild.CommandParameter = viewModel.CommandParameter;

            BindingsTreeView.DataContext = viewModel;
            BindingsTreeView.Focus();

            var timer = new DispatcherTimer();

            timer.Tick += (sender2, e2) =>
            {
                if (!waiting) // Monitor.TryEnter not working
                {
                    waiting = true;

                    try
                    {
                        var operation = context.GetStatusMessages();

                        operation.Completed += (sender3, e3) =>
                        {
                            try
                            {
                                var messages = operation.Value;

                                if (messages != null)
                                {
                                    messages.ToList().ForEach(m => messageQueue.Enqueue(m));
                                }
                            }
                            catch (Exception ex)
                            {
                                messageQueue.Enqueue(ex.Message);
                            }

                            waiting = false;
                        };
                    }
                    catch (Exception ex)
                    {
                        messageQueue.Enqueue(ex.Message);
                    }
                }

                if (messageQueue.Count > 0)
                {
                    ProviderClientManager.SetStatus(messageQueue.Dequeue());
                }
            };

            timer.Interval = new TimeSpan(0, 0, 0, 0, 1000); // one second
            timer.Start();
        }

        private void TreeView_OnStatus(ITreeNode treeNode, string status)
        {
            if (status != null && status.Length > 0)
            {
                ProviderClientManager.SetStatus("Data Type: " + status);
            }
            else
            {
                ProviderClientManager.SetStatus(status);
            }
        }

        private void TreeView_Busy(ITreeNode treeNode, bool busy)
        {
            if (busy)
            {
                ProviderClientManager.SetStatus(treeNode.Text + " loading...");
            }
            else
            {
                ProviderClientManager.SetStatus("");
            }
        }
    }
}
